---
title: "Reading Files"
output:
  ioslides_presentation: default
  smaller: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


## Outline
- Reading files: Excel and .csv


## Importing Data

We often need to import in our own data rather than just using built-in datasets.

- First need to tell R where the data is saved using `setwd()`
- Data read in using R functions such as:
    - `read.table()` for reading in .txt files
    - `read.csv()` for reading in .csv files
- Assign the data to new R object when reading in the file

## Importing Data Demo

We first create a .csv file. We can use a text editor, excel... Then we load it in:

```{r, eval=FALSE}
setwd(/pathtodirectory)
```
```{r}
nfl <- read.csv("NFL Games.csv")
```


## Data in Excel
Formats xls and csv - what's the difference? File extensions .xls or .xlsx are proprietary Excel formats, they are binary files .csv is the extension for comma separated value files. They are text files - and directly readable.


## Excel file in Excel

<center><img src="excelinexcel.png" width="600px"></center>


## Excel file in notepad
<center><img src="excelnp.png" width="600px"></center>


## .csv file in notepad
<center><img src="csvexample.png" width="600px"></center>


## Reading Files in R

Text files, usually comma separated or tabular separated (space) can both be read in with `read.csv()`

```{r,eval = F}
read.csv(file, header = TRUE, sep = ",", quote = "\\"",
 dec = ".", fill = TRUE, comment.char = "", ...)
```
For a comma separated file, we set `sep = ","` else for a tabular separated file use `sep = ""`

## Reading .csv File
 
```{r}
nba <- read.csv("NBA Draft Class.csv")
head(nba)
```

```{r}
str(nba)
```


## Reading Excel File
Need another package: `readxl`

```{r,eval =F}
install.packages(readxl)
```

```{r}
library(readxl)

nba2 <- read_excel("NBA_Playoffs.xlsx",sheet = 1)
head(nba2)

```

## Your Turn
Using the NFL Games.csv file, do the following:

1. Read the data into an object called nfl. 

2. Use the `head()` function to display some rows.

3. Use the `str()` function to see each variable type.


## Answers

### 1.
```{r}
nfl <- read.csv("NFL Games.csv")
```

##
### 2.
```{r}
head(nfl)
```

##
### 3.
```{r}
str(nfl)
```



